/**
 * Created by bianlian on 16/9/19.
 */

import React, { Component, PropTypes } from 'react';
import {
    AppRegistry,
    StyleSheet,
    View,
    ListView,
    Text,
    Image,
    TouchableOpacity,
    BackAndroid,
    Platform,
    FlatList,
    NativeModules,
	AsyncStorage,
    ScrollView,
    StatusBar
} from 'react-native';
var RNBridgeModule= NativeModules.RNBridgeModule;
import { bindActionCreators } from 'redux';
import {connect} from 'react-redux';
import { MtContainer, MtListView, MtSeparator, MtChar,MtNavBar, MtEmptyView, MtColor,MtButton, MtLoadingModal } from 'martian-ui';
const { MtT1, MtLabel, MtL3, MtT3 } = MtChar;
import DropDownModal from '../components/DropDownModal';
import ConditionButton from '../components/ConditionButton';
import CommonRoomlist from '../components/commonRoomlist';
import CameraList from '../components/CameraList';
import ShowEnergyUsage from '../components/ShowEnergyUsage';
const YaguanRoomListCell = require('../components/YaguanHomeListCell');
import SplashScreen from 'react-native-splash-screen'
import GirlDetail from '../container/girlDetail';
import {fetchHouseList, fetchRoomList, fetchUserInfo, fetchScenesInfo} from '../action/girlAction';
import Dimensions from 'Dimensions';
const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height / 2;
import keys from 'lodash/keys';
import assign from 'lodash/assign';
const EntityLabels = require('../constants/entities');
import { mappingToEntities } from '../store/subStore';

import values from 'lodash/values';
import ScrollableTabView, { ScrollableTabBar, DefaultTabBar } from 'react-native-scrollable-tab-view';
import CombinedButton from 'react-native-combined-button';
import ModalDropdown from 'react-native-modal-dropdown';
import FamilyTransfer from './Mine/FamilyTransfer'
import ScanIos from './Mine/ScanIos'
import { Icon } from '../components/common/icon'
import NavigationBar from '../components/common/NavigationBar'
import getIcon from '../components/common/icon/iconFontMap'

const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? (Dimensions.get('window').height === 812 ? 30 : 20) : (StatusBar.currentHeight || 25);
const HEADER_HEIGHT = Platform.OS === 'ios' ? 44 + STATUS_BAR_HEIGHT : 50 + (Platform.Version >= 21 ? 0: 0);
const DEMO_OPTIONS = [{name: '扫一扫', component: ScanIos},{name: '家庭转换', component: FamilyTransfer}]

function _renderRow(room, sectionID, rowID) {
    const { navigator, roomReducer } = this.props;
    return (
        <YaguanRoomListCell
            navigator={navigator}
            room={room}
            isFetching={roomReducer.loading}

        />
    );
}
class YaguanHome extends Component {

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            label: ['一楼', '二楼','三楼', '四楼', '五楼','地下室','一楼', '二楼','三楼', '四楼', '五楼','地下室' ],
            tabShow: false,
        };
        this._refreshMsssage = this._refreshMsssage.bind(this)
        this.dataSource = new ListView.DataSource({
            rowHasChanged: ((row1, row2) => row1 !== row2)
        })
    }

    /**
     * 调用数据 :
     *      1. 当触发Action方法请求数据反馈到Reducer中
     *      2. Reducer通过ActionType判断该更新哪个UI中的State
     *      3. 最后刷新界面显示数据
     */
    componentWillMount() {
        // SplashScreen.hide();//关闭启动屏幕
        // RNBridgeModule.login("bianbian","123456").then((events)=>{
        //     console.warn(JSON.stringify(events));
        // }).catch((e)=>{
        //     console.warn(e);
        // })
        this.convertPropsToStates(this.props);
        // this.goAlinkLoginpage()
        if (Platform.OS === 'android') {

            BackAndroid.addEventListener('hardwareBackPress', () => this.onBackAndroid());
        }
    }

    componentDidMount() {
		this.props.fetchHouseList();

        if (Platform.OS === 'android') {
            BackAndroid.addEventListener('hardwareBackPress', () => this.onBackAndroid());
        }
        setTimeout(() => {
            this.setState({
                tabShow: true
            });
        }, 0)

        // this.refresh();
    }



    getQuanWuScence(){


    }

    convertPropsToStates(props) {
        const { scenesEntities, houseEntities, tip } = props;
        const { currentHouse } = this.state;
        let newScenesArr =[];
        let houseList;
        if (scenesEntities && keys(scenesEntities).length > 0 && currentHouse && currentHouse.gatewayList && currentHouse.gatewayList.length > 0 ) {
            const scenesArr = values(scenesEntities);
            const productKey = currentHouse.gatewayList[0] && currentHouse.gatewayList[0].productKey;

            newScenesArr = scenesArr.filter(
                    ele => ele.productKey === productKey
                )
        }
        if (houseEntities && keys(houseEntities).length > 0) {
            houseList = values(houseEntities);
            const currentHouse2 = houseList[0];
            if (!currentHouse) {
                this._fetchScenesInfo(currentHouse2);
              this.getRoomAndDevice(currentHouse2 && currentHouse2.id);
                this.setState({currentHouse: currentHouse2 });
            }
        }
        const newState = assign({
            newScenesArr,
            houseList,
            tip
        });
        this.setState(newState);
    }

    componentWillReceiveProps(nextProps) {
        this.convertPropsToStates(nextProps);
    }

    _fetchScenesInfo(house) {
        if (house.gatewayList.length > 0) {
            const gateway = house.gatewayList[0];
            const { deviceId } = gateway;
            const {assessToken} =this.props;
            this.props.fetchScenesInfo(deviceId);
        }

    }

    getRoomAndDevice(houseID) {
        const {fetchRoomList, assessToken} = this.props;
        fetchRoomList(houseID, assessToken);
    }

    /**
     * 监听Android返回按键
     * @returns {boolean}
     */
    onBackAndroid() {

        const {navigator} = this.props;
        if (navigator.getCurrentRoutes().length > 1) {
            navigator.pop();
            return true;
        }
        //退出
        return false;

    }

    async goEzCamera(){
        RNBridgeModule.popToEZCamera('210715859').then((events)=>{

        }).catch((e)=>{
            console.warn(e);
        })
    }

    async goAlinkLoginpage(){
        const {dispatch, userReducer, fetchUserInfo} = this.props;

        RNBridgeModule.RNOpenAlink('bianbian').then((events)=>{
            this.setState({ mobile: events.mobile})
            fetchUserInfo(events);

            // fetchUserInfo(events);
        }).catch((e)=>{
            console.warn(e);
        })
    }
    //针对 全屋场景
    renderQuanwuScence() {
        const {newScenesArr} = this.state;
        const quanWuScene = newScenesArr || [];
      if(!newScenesArr || newScenesArr.length <= 0) {
        return
      }
        return (
            <View style={styles.moduleBox}>
                <FlatList
                    data={quanWuScene}
                    keyExtractor={(item, index) => index}
                    renderItem={this.renderQuanwuScenceItem}
                    horizontal={true}
                    showsHorizontalScrollIndicator={false}
                />
            </View>
        )
    }
    _refreshMsssage= (id) =>{
        const { currentHouse } = this.state;
        this.setState({isPress:id});
///临时处理方案 强制 从根结点 重渲染
        const id1 = currentHouse.gatewayList[0] && currentHouse.gatewayList[0].deviceId;
        this.props.fetchScenesInfo(id1);

    };

    renderQuanwuScenceItem = ({ item }) => {
        let icon = getIcon(item.name)
        return (
            <TouchableOpacity onPress={() => {
                this._refreshMsssage(item.id)
              }}
            >
              <View style={[styles.scenceItem, {backgroundColor: this.state.isPress == item.id ? '#28B9C8' : '#ffffff'}]}>
                <Icon name={icon.name} size={32} color={this.state.isPress == item.id ? '#FFFFFF' : '#888888'} />
                <Text style={[styles.scenceItemName, {color: this.state.isPress == item.id ? '#FFFFFF' : '#888888'}]}>{item.name}</Text>
              </View>
            </TouchableOpacity>
        )
    };


    //针对常用房间

    // 滑动tab
    renderScrollableTab() {
    	const {assessToken} = this.props;
        const {currentHouse, label,tabShow } =this.state;

            return (
                <ScrollableTabView
                    renderTabBar={() =>
                        <ScrollableTabBar
                            style={{height:44}}
                            tabStyle={{height:44,paddingLeft: 15,paddingRight: 15, paddingVertical: 12}}
                        />
                    }
                    tabBarBackgroundColor='#FFFFFF'
                    tabBarActiveTextColor='#00A5AD'
                    tabBarInactiveTextColor='#CCCCCC'
                    tabBarUnderlineStyle={styles.tabBarUnderline}
                >
                    {
                        label.map((item, index) => {
                            return (
                                <ScrollView tabLabel={item} key={index}>
                                    {currentHouse && currentHouse.id &&(
                                        <View>
                                            <CommonRoomlist
                                                id={ currentHouse.id}
												                        assessToken={assessToken}
                                                gatewayId={currentHouse.gatewayList.length > 0 && currentHouse.gatewayList[0].deviceId}
                                                productKey = {currentHouse.gatewayList[0] && currentHouse.gatewayList[0].productKey}
                                                deviceName = {currentHouse.gatewayList[0] && currentHouse.gatewayList[0].deviceName}
                                                navigator={this.props.navigator}
                                            />
                                            {
                                                <CameraList
                                                />
                                            }
                                            {

                                                <ShowEnergyUsage
                                                />
                                            }
                                        </View>
                                    )}


                                </ScrollView>
                                )

                        })
                    }
                </ScrollableTabView>
            )
    }

    render() {
        //此reducer为index注册中的,取指定reducer取数据
        const { roomIsFetching, scenceIsFetching, navigator } = this.props;
        const { currentHouse, houseList, tip } = this.state;
        const renderRowBind = _renderRow.bind(this);

        const leftItem = <ConditionButton
                    ref={
                        (button) => {
                            this.sdtBtn = button;
                        }
                    }
                    title={currentHouse && currentHouse.name ||  '房屋列表'}
                    checked={currentHouse}
                    onSelect={(selected) => {
                        onClose(this, 5);
                        if (selected) {
                            //this.getRelationSdt();
                            this.sdtModal.open();
                        }
                        else {
                            this.sdtModal.close();
                        }
                    }}
                />

        const rightButton = <TouchableOpacity onPress={this.handleRightPress.bind(this)} style={{ marginRight: 10}}>
                                 <Icon name='icon_shezhi' size={32} color="#666666" />
                            </TouchableOpacity>

        const Navi = (
            <View style={{ flexDirection: 'row', paddingTop: 15, alignItems: 'center'}}>
                {tip ==='home' && <StatusBar backgroundColor='#F4F4F4' barStyle='dark-content'/>}
                {leftItem}
                {rightButton}
            </View>
        )
        console.warn('tip'+ this.state.tip);
        return (
            <View style={styles.container}>
                <MtLoadingModal
                    visible={roomIsFetching || scenceIsFetching}
                    tip="加载中"
                />
                {Navi}
                {this.renderQuanwuScence()}
                {this.renderScrollableTab()}


                <DropDownModal
                    key="sdtModal"
                    marginTopHeight={MtNavBar.height}
                    ref={(modal) => {
                        this.sdtModal = modal;
                    }}
                    onSelect={
                        (item) => {
                          this.setState({currentHouse: item});
                          this.getRoomAndDevice(item.id);
                          this._fetchScenesInfo(item);
                          this.setState({isPress:0});
                          this.sdtModal.close();

                        }
                    }
                    onClosed={()=>{
                    }}
                    options={houseList || []}
                    selectedOption={currentHouse}
                    transformOption={option => option.name}
                    testOptionEqual={(a, b) => a.id === b.id}
                />

                <ModalDropdown
                  key="modalDropdown"
                  options={DEMO_OPTIONS}
                  ref={el => this.modalDropdown = el}
                  dropdownStyle={styles.dropdownStyle}
                  adjustFrame={style => this._dropdown_adjustFrame(style)}
                  renderRow={this._dropdown_renderRow.bind(this)}
                  renderSeparator={(sectionID, rowID, adjacentRowHighlighted) => this._dropdown_renderSeparator(sectionID, rowID, adjacentRowHighlighted)}
                  onSelect={
                    (idx, value) => {
                      this.modalDropdown.hide()
                      navigator.push({
                        component: value.component,
                        params: {

                        }
                    })
                    }
                  }
                />
            </View>
        )
    }

    handleRightPress() {
      this.modalDropdown.show()
    }

    _dropdown_renderRow(rowData, rowID, highlighted) {
      return (
        <TouchableOpacity>
          <View style={styles.dropItem}>
            <Text style={styles.dropItemText}>
              {`${rowData.name}`}
            </Text>
          </View>
        </TouchableOpacity>
      )
    }

    _dropdown_renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
      if (rowID == DEMO_OPTIONS.length - 1) return;
      let key = `spr_${rowID}`;
      return (<View style={styles.dropdown_separator}
                    key={key}
      />);
    }

    _dropdown_adjustFrame(style) {
      console.warn(JSON.stringify(style))
      style.top = HEADER_HEIGHT;
      style.left = width - 80;
      return style;
    }
}
function onClose(me, idx) {
    if (idx !== 5) {
        me.sdtBtn.clean();
        me.sdtModal.close();
    }
}
const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: '#FFFFFF',
    },
    moduleBox: {
        width: width,
        alignItems:'flex-start',
        paddingTop: 20,
        paddingBottom: 20,
        paddingLeft: 15,
    },
    subtitle:{
        fontSize:16,
        color:'#666',
        padding:15,
    },
    iconBtn: {
        margin: 8,
        borderWidth: 0,
        backgroundColor: '#FFFFFF'
    },
    barStyle: {
        height: 55,
        flexDirection: 'row',
        marginHorizontal: 15,
        alignItems: 'center',
    },
    btnContainer: {
        width: 150,
        height: 40,
        borderRadius: 20,
        marginLeft: 10,
        marginRight: 10,
        marginTop: 10,
        marginBottom: 10,
    },
    textStyle: {
        borderRadius: 20,
        marginHorizontal: 7,
        fontSize: 16,
    },
    tabBarUnderline: {
        backgroundColor: '#00A5AD',
        height: 2,
        width:width/8,
        marginLeft:6
    },
    dropdownStyle: {
      width: 80,
      height: 100
    },
    dropItem: {
      height: 32,
      alignItems: 'center',
		  justifyContent: 'center',
    },
    dropItemText: {

    },
    dropdown_separator: {
      height: 1,
      backgroundColor: 'cornflowerblue',
    },
    scenceItem: {
      width: 70,
      height: 70,
      justifyContent: 'center',
      alignItems: 'center',
      marginRight: 10,
      backgroundColor: '#28B9C8',
      borderRadius: 6,
    },
    scenceItemName: {
      fontSize: 11,
      color: '#888888',
      marginTop: 6,
    }
});
function mapStateToProps(state, ownProps) {
    const {roomReducer, userReducer} = state;
    const entities= state['entities'];
    const isFetching= state['isFetching'];

    const houseEntities = entities[EntityLabels.house];
    const scenesEntities = entities[EntityLabels.scenes];
    const houseIsFetching = isFetching[EntityLabels.house];
    const roomIsFetching = isFetching['getRoomList'];
    const scenceIsFetching = isFetching['getScenceList'];


    const house = houseEntities && values(houseEntities);

    // console.warn('mapStateToProps' + JSON.stringify(scenes))

    return {
        houseEntities,
        scenesEntities,
        //house,
        //roomReducer,
        userReducer,
        houseIsFetching,
        roomIsFetching,
        scenceIsFetching,
    }
}
function mapDispatchToProps(dispatch) {
    const actions = {
        fetchHouseList,
        fetchRoomList,
        fetchUserInfo,
        fetchScenesInfo,
    };
    return bindActionCreators(actions, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(YaguanHome);
